package com.android.manghe.mine.activity

import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.Glide.GlideCacheUtil
import com.android.base.tools.PackageUtil
import com.android.base.tools.PathUtil
import com.android.base.tools.ToastUtil
import com.android.base.tools.permission.OnPermissionResultListener
import com.android.base.tools.permission.PermissionUtil
import com.android.manghe.R
import com.android.manghe.cache.UserHolder
import com.android.manghe.common.webview.ERefreshWebType
import com.android.manghe.common.webview.WebViewActivity
import com.android.manghe.common.webview.WebViewParameter
import com.android.manghe.config.Config
import com.android.manghe.main.MainActivity
import com.android.manghe.mine.presenter.PSetting
import com.android.manghe.service.DownloadService
import com.android.manghe.view.dialog.NewTipDialog
import com.android.manghe.view.dialog.UpdateDialog
import com.tencent.bugly.beta.Beta
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_setting.*

class SettingActivity : MVPActivity<PSetting>() {

    private var mProgressDialog: ProgressDialog? = null;

    companion object {
        fun showActivity(context: Context) {
            val intent = Intent(context, SettingActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_setting
    }

    override fun initData(savedInstanceState: Bundle?) {
        titleBar.setToolbar("设置").setTitleAndStatusBgColor(R.color.white).hideBottomLine()
            .setLeftIcon(R.mipmap.icon_back_black)
        tvVersion.text = "V" + PackageUtil.getVersionName(this)
        tvCacheSize.text = GlideCacheUtil.getInstance().getCacheSize(this)

        if (UserHolder.getUserInfo(this) == null) {
            tvFeedBack.visibility = View.GONE
            btnLogout.visibility = View.GONE
        }

        initListener()
    }

    private fun initListener() {
        tvFeedBack.setOnClickListener {
            open(FeedbackActivity::class.java)
        }
        layoutClearCache.setOnClickListener {
            GlideCacheUtil.getInstance().clearImageAllCache(this)
            tvCacheSize.text = "0M"
        }
        aboutUs.setOnClickListener {
            WebViewActivity.showActivity(
                mContext, WebViewParameter.WebParameterBuilder()
                    .setUrl("https://www.manghe98.com/about_us/index.html")
                    .setShowProgress(true)
                    .setCanHistoryGoBackOrForward(true)
                    .setReloadable(true)
                    .setReloadType(ERefreshWebType.ClickRefresh)
                    .setCustomTitle("关于我们")
                    .build()
            )
        }
        layoutCheckVersion.setOnClickListener {
            val info = Beta.getUpgradeInfo()
            if (info != null && info.versionCode > PackageUtil.getVersionCode(this)) {
                Beta.checkUpgrade(false, false)
            } else {
                alreadyLastedVersion()
            }
//            showLoadingDialog()
//            p.checkVersion()
        }
        btnLogout.setOnClickListener {
            val mDialog = NewTipDialog(this, "确定退出登录吗")
            mDialog.show()
            mDialog.setListener(object : NewTipDialog.ITipDialogListener {
                override fun clickRight() {
                    doSignOut()
                }

                override fun clickLeft() {

                }
            })
        }

        tvServiceDoc.setOnClickListener {
            //用户服务协议
            WebViewActivity.showActivity(
                mContext, WebViewParameter.WebParameterBuilder()
                    .setUrl("https://www.manghe98.com/protocol/user_service.html")
                    .setShowProgress(true)
                    .setCanHistoryGoBackOrForward(true)
                    .setReloadable(true)
                    .setReloadType(ERefreshWebType.ClickRefresh)
                    .setCustomTitle("用户服务协议")
                    .build()
            )
//            open(AgreementActivity::class.java, hashMapOf<String,Any>("type" to 1))
        }
        tvSecretDoc.setOnClickListener {
            //隐私政策
            WebViewActivity.showActivity(
                mContext, WebViewParameter.WebParameterBuilder()
                    .setUrl("https://www.manghe98.com/protocol/privacy.html")
                    .setShowProgress(true)
                    .setCanHistoryGoBackOrForward(true)
                    .setReloadable(true)
                    .setReloadType(ERefreshWebType.ClickRefresh)
                    .setCustomTitle("隐私政策")
                    .build()
            )
//            open(AgreementActivity::class.java, hashMapOf<String,Any>("type" to 0))
        }

        tvAccountSafe.setOnClickListener {
            //账号安全
            open(AccountSafeActivity::class.java)
        }

        tvCommonProblem.setOnClickListener {
            //常见问题
            open(CommonProblemActivity::class.java)
        }

        tvPermission.setOnClickListener {
            //隐私设置
            open(SettingPermissionActivity::class.java)
        }
    }

    fun doSignOut() {
        UserHolder.clearInfo(this)
//                Bus.send(RefreshUserInfoEvent())
        UMShareAPI.get(mContext).deleteOauth(this@SettingActivity, SHARE_MEDIA.WEIXIN, null)
        UMShareAPI.get(mContext).deleteOauth(this@SettingActivity, SHARE_MEDIA.QQ, null)
        open(MainActivity::class.java)
    }

    fun showGetUpdateFailMsg(text: String?) {
        ToastUtil.showShort(this, if (TextUtils.isEmpty(text)) "获取更新信息失败" else text)
    }

    fun alreadyLastedVersion() {
        ToastUtil.showShort(this, "已是最新版本")
    }

    fun showUpdateDialog(versionName: String, content: String, url: String) {
        UpdateDialog.showDialog(
            this,
            versionName,
            content,
            url,
            object : UpdateDialog.Companion.IUpdateDialogListener {
                override fun clickUpdate(url: String) {
                    PermissionUtil.requestPermissions(
                        this@SettingActivity, OnPermissionResultListener {
                            PathUtil.makeDirs(Config.AppUpdatePath)
                            DownloadService.start(
                                this@SettingActivity,
                                url,
                                Config.AppUpdatePath,
                                true,
                                object : DownloadService.IDownloadServiceListener {
                                    override fun onFailure() {
                                        mProgressDialog?.dismiss()
                                        ToastUtil.showShort(this@SettingActivity, "下载失败")
                                    }

                                    override fun onStart() {
                                        mProgressDialog = ProgressDialog(this@SettingActivity)
                                        mProgressDialog!!.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
                                        mProgressDialog!!.setTitle("下载中...")
                                        mProgressDialog!!.max = 100
                                        mProgressDialog!!.show()
                                        ToastUtil.showShort(this@SettingActivity, "开始下载")
                                    }

                                    override fun onLoading(progress: Int) {
                                        mProgressDialog?.progress = progress
                                    }

                                    override fun onSuccess() {
                                        mProgressDialog?.dismiss()
                                        ToastUtil.showShort(this@SettingActivity, "下载完成")
                                    }

                                })
                        },
                        Permission.WRITE_EXTERNAL_STORAGE
                    )
                }
            })
    }

    public override fun onDestroy() {
        super.onDestroy()
    }
}